package demo2;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


public class TcpThreadPoolServer {
    //服务器使用的socket
    private ServerSocket serverSocket = null;

    public TcpThreadPoolServer(int port) throws IOException {
        //创建服务端,用于接收TCP报文
        serverSocket = new ServerSocket(port);
    }

    //启动服务器
    private void start() throws IOException {
        System.out.println("服务器启动");
        ExecutorService service = Executors.newCachedThreadPool();
        while(true){//服务器长时间运行
            Socket clientSocket = serverSocket.accept();
            service.submit(new Runnable() {
                @Override
                public void run() {
                    try {
                        processConnection(clientSocket);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    }
    private void processConnection(Socket clientSocket) throws IOException {
        System.out.printf("[%s : %d] 建立连接\n",clientSocket.getInetAddress().toString()
                ,clientSocket.getPort());
        try(InputStream inputStream = clientSocket.getInputStream();
            OutputStream outputStream = clientSocket.getOutputStream()){
            Scanner scanner = new Scanner(inputStream);//用于接收数据
            PrintWriter printWriter = new PrintWriter(outputStream);//用于发送数据
            while(true){
                if(!scanner.hasNext()){
                    //如果读到结束符就断开连接
                    System.out.printf("[%s : %d] 断开连接\n",clientSocket.getInetAddress().toString()
                            ,clientSocket.getPort());
                    break;
                }
                //接收请求并且解析
                String request = scanner.next();
                //根据请求做出响应==>回显
                String response = process(request);
                //将响应发送给客户端===>这里要发送时加上空格==>防止next阻塞
                printWriter.println(response);
                printWriter.flush();//不要忘记双薪缓冲区
                System.out.printf("[%s : %d] 发送成功 req : %s ; rep : %s\n",clientSocket.getInetAddress().toString()
                        ,clientSocket.getPort(),request,response);
            }
        }catch(IOException e){
            e.printStackTrace();
        }finally {
            clientSocket.close();
        }
    }
    //回显服务器==>客户端做出什么请求就给什么样的响应
    private String process(String request){
        return request;
    }

    public static void main(String[] args) throws IOException {
        TcpThreadPoolServer tcpThreadPoolServer = new TcpThreadPoolServer(8000);
        tcpThreadPoolServer.start();
    }


}
